package com.pactera.miyuangroup.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.config.CommonConfig;
import com.pactera.miyuangroup.db.entity.*;
import com.pactera.miyuangroup.db.enums.DeliveryType;
import com.pactera.miyuangroup.db.enums.ShowState;
import com.pactera.miyuangroup.db.mapper.VehicleInfoMapper;
import com.pactera.miyuangroup.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pactera.miyuangroup.vo.convertor.VehicleInfoConvert;
import com.pactera.miyuangroup.vo.convertor.VendorInfoConvert;
import com.pactera.miyuangroup.vo.request.web.PageDeliverymanAdjustReq;
import com.pactera.miyuangroup.vo.request.web.UpdateDeliverymanAdjustReq;
import com.pactera.miyuangroup.vo.request.web.VehicleInfoRequest;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanModel;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanPage;
import com.pactera.miyuangroup.vo.response.miyuan.UserInfo;
import com.pactera.miyuangroup.vo.response.web.PageDeliverymanAdjustRes;
import com.pactera.miyuangroup.vo.response.web.VehicleInfoRes;
import com.pactera.miyuangroup.vo.response.web.VendorInfoRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 车辆信息 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class VehicleInfoServiceImp extends ServiceImpl<VehicleInfoMapper, VehicleInfo> implements VehicleInfoService {

    @Autowired
    private VehicleInfoConvert vehicleInfoConvert;

    @Autowired
    private VendorInfoConvert vendorInfoConvert;

    @Autowired
    private VendorInfoService vendorInfoService;

    @Autowired
    private OrganizationStructureService organizationStructureService;

    @Autowired
    private VehicleUserService vehicleUserService;

    @Autowired
    private RedisOperation redis;
    @Autowired
    private MiyuanDataService miyuanDataService;


    @Override
    public Page<VehicleInfoRes> getVehicleInfoList(VehicleInfoRequest vehicleRequest, String ordId) {
        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        if (!Constants.SYS_ROOT.equals(ordId)) {
            wrapper.eq("organization_id", ordId);
        }
        if (StringUtils.isNotBlank(vehicleRequest.getLicensePlate())) {
            wrapper.like("license_plate", vehicleRequest.getLicensePlate());
        }

        if (StringUtils.isNotBlank(vehicleRequest.getOrganizationName())) {
            wrapper.like("name", vehicleRequest.getOrganizationName());
        }

        if (StringUtils.isNotBlank(vehicleRequest.getLineNumber())) {
            wrapper.like("line_number", vehicleRequest.getLineNumber());
        }

        if (StringUtils.isNotBlank(vehicleRequest.getLineName())) {
            wrapper.like("line_name", vehicleRequest.getLineName());
        }

        //查询数据
        Page<VehicleInfoRes> VehicleInfoRes = new Page<VehicleInfoRes>(vehicleRequest.getCurrent(), vehicleRequest.getSize());

        List<VehicleInfoRes> VehicleInfoResListDO = baseMapper.selectVehicleInfoResList(VehicleInfoRes, wrapper);

        //DO 转 PO
        List<VehicleInfoRes> VehicleInfoResListPO = vehicleInfoConvert.convert2VehicleInfoRes(VehicleInfoResListDO);


        VehicleInfoRes.setRecords(VehicleInfoResListPO);

        return VehicleInfoRes;
    }

    @Override
    public List<VendorInfoRes> getVendorInfoList(String vehicleId) {
        //验证数据

        if (StringUtils.isNotBlank(vehicleId)) {
            //查询数据
            List<VendorInfo> VendorInfoDO = new ArrayList<>();
            EntityWrapper<VendorInfo> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("vehicle_id", vehicleId);
            VendorInfoDO = vendorInfoService.selectList(entityWrapper);

            List<VendorInfoRes> VendorInfoResList = vendorInfoConvert.convert2VehicleInfoRes(VendorInfoDO);

            return VendorInfoResList;
        }
        return null;
    }

    /**
     * 查询售货机人员调整列表
     *
     * @param req
     * @param org
     * @return
     */
    @Override
    public Page<PageDeliverymanAdjustRes> selectListPage(PageDeliverymanAdjustReq req, String org) {
        Page<PageDeliverymanAdjustRes> pageList = new Page<>(req.getCurrent(), req.getSize());
        EntityWrapper ew = new EntityWrapper();
        if (!Constants.SYS_ROOT.equals(org)) {
            ew.eq("A.organization_id", org);
        }
        //车牌
        if (StringUtils.isNotBlank(req.getLicensePlate())) {
            ew.like("license_plate", req.getLicensePlate());
        }
        //姓名
        if (StringUtils.isNotBlank(req.getName())) {
            ew.like("name", req.getName());
        }
        //工号
        if (StringUtils.isNotBlank(req.getJobNumber())) {
            ew.eq("job_number", req.getJobNumber());
        }
        //电话
        if (StringUtils.isNotBlank(req.getPhone())) {
            ew.eq("phone", req.getPhone());
        }
        List<PageDeliverymanAdjustRes> page = baseMapper.selectListDeliverymanAdjust(pageList, ew);
        pageList.setRecords(page);
        return pageList;
    }


    /**
     * 车辆用户分配
     *
     * @param vehicleId 车辆ID
     * @param createrId 操作人ID
     * @param req
     * @return
     */
    @Override
    @Transactional
    public boolean vehicleAdjustUser(String vehicleId, String createrId, UpdateDeliverymanAdjustReq req) {
        boolean flg = false;
        VehicleInfo vehicleInfo = selectById(vehicleId);
        if (null == vehicleInfo) {
            return flg;
        }
        vehicleInfo.setUserId(req.getUserId());
        vehicleInfo.setRelationship(req.getDeliveryType());
        vehicleInfo.setAdjustTime(new Date());
        if (req.getDeliveryType().equals(DeliveryType.FIXED)) {
            //固定
            vehicleInfo.setEffectTime(new Date());
            vehicleInfo.setInvalidTime(com.pactera.miyuangroup.util.Date.get2099Year());
        } else {
            //临时
            vehicleInfo.setEffectTime(com.pactera.miyuangroup.util.Date.parseDate(req.getEffectTime()));
            vehicleInfo.setInvalidTime(com.pactera.miyuangroup.util.Date.parseDate(req.getInvalidTime()));
        }
        flg = updateById(vehicleInfo);
        if (!flg) {
            return flg;
        }
        //新增调整记录
        VehicleUser vehicleUser = new VehicleUser();
        vehicleUser.setUserId(req.getUserId());
        vehicleUser.setVehicleId(vehicleInfo.getId());
        vehicleUser.setRelationship(vehicleInfo.getRelationship());
        vehicleUser.setAdjustTime(vehicleInfo.getAdjustTime());
        vehicleUser.setEffectTime(vehicleInfo.getEffectTime());
        vehicleUser.setInvalidTime(vehicleInfo.getInvalidTime());
        vehicleUser.setCreater(createrId);
        flg = vehicleUserService.insert(vehicleUser);
        //
        //
        return flg;
    }

    /**
     * 车辆
     *
     * @return
     */
    @Override
    public boolean syncMiyuanVehicleInfo() {
        //开始更新
        boolean flg = redis.get(Constants.REDIS_MIYUAN_VEHICLE_INFO_SYNC, Boolean.class, Boolean.TRUE);
        if (!flg) {
            return false;
        }
        //使用多线程
        miyuanDataService.executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    redis.set(Constants.REDIS_MIYUAN_VEHICLE_INFO_SYNC, Boolean.FALSE);
                    miYuanVehicleInfo();
                    redis.set(Constants.REDIS_MIYUAN_VEHICLE_INFO_SYNC, Boolean.TRUE);
                } catch (Exception e) {
                    log.error("同步米源车辆信息发生异常", e);
                    redis.set(Constants.REDIS_MIYUAN_VEHICLE_INFO_SYNC, Boolean.TRUE);
                }
            }
        });
        return true;
    }

    @Override
    public void syncMiyuanVehicleSchedulerInfo() {
        miYuanVehicleInfo();
    }


    /**
     * 同步米源数据
     */
    private void miYuanVehicleInfo() {
        int n = 1;
        MiYuanModel<MiYuanPage<com.pactera.miyuangroup.vo.response.miyuan.VehicleInfo>> vehicleInfos = miyuanDataService.getVehicleInfo(n, 100);
        while (true) {
            n++;
            //是否成功
            //失败，跳出，继续下一页
            if (!vehicleInfos.isSuccess()) {
                continue;
            }

            //验证是否有数据，没有数据 跳出 继续下一页
            if (vehicleInfos.getData() == null || vehicleInfos.getData().getRecords() == null && vehicleInfos.getData().getRecords().size() <= 0) {
                continue;
            }

            //更新用户集合
            List<VehicleInfo> upInfos = new ArrayList<>();
            //新增用户集合
            List<VehicleInfo> instInfos = new ArrayList<>();

            //循环数据入库
            for (com.pactera.miyuangroup.vo.response.miyuan.VehicleInfo vehicleInfo : vehicleInfos.getData().getRecords()) {
                //查询数据库是否存在数据
                EntityWrapper<VehicleInfo> ew = new EntityWrapper<>();
                if (StringUtils.isNotBlank(vehicleInfo.getLicensePlate())) {
                	ew.eq("license_plate", vehicleInfo.getLicensePlate());
                } else {
                	ew.eq("original_id", vehicleInfo.getId()); 
                }
                VehicleInfo info = selectOne(ew);

                //查询车辆所属机构
                EntityWrapper<OrganizationStructure> orgew = new EntityWrapper<>();
                orgew.eq("original_id", vehicleInfo.getOrganizationId());
                OrganizationStructure orgInfo = organizationStructureService.selectOne(orgew);
                String orgId = "";
                if (null != orgInfo) {
                    orgId = orgInfo.getId();
                }

                if (null != info) {
                    //存在，更新数据
                    info.setLicensePlate(vehicleInfo.getLicensePlate());
                    info.setPrecinct(vehicleInfo.getPrecinct());
                    info.setOrganizationId(orgId);
                    info.setLineNumber(vehicleInfo.getLineNumber());
                    info.setLineName(vehicleInfo.getLineName());
                    info.setOriginalId(vehicleInfo.getId());
                    upInfos.add(info);
                } else {
                    //不存在，新增数据
                    info = new VehicleInfo();
                    info.setLicensePlate(vehicleInfo.getLicensePlate());
                    info.setPrecinct(vehicleInfo.getPrecinct());
                    info.setOrganizationId(orgId);
                    info.setLineNumber(vehicleInfo.getLineNumber());
                    info.setLineName(vehicleInfo.getLineName());
                    info.setOriginalId(vehicleInfo.getId());
                    instInfos.add(info);
                }
            }

            //更新
            if (upInfos.size() > 0) {
                updateBatchById(upInfos, upInfos.size());
            }
            //新增
            if (instInfos.size() > 0) {
                insertBatch(instInfos, instInfos.size());
            }

            //最后一页，退出
            if (vehicleInfos.getData().isLast()) {
                break;
            }
            vehicleInfos = miyuanDataService.getVehicleInfo(n, 100);
        }
    }
}
